package com.greenhouse.utily;

import com.greenhouse.model.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

public class SessionUtils {

    /**
     * 设置Session中的用户信息
     * @param request
     * @param user
     */
    public static void setSessionUser(HttpServletRequest request, User user) {
        request.getSession().setAttribute(ConstantUtils.USERINFO_SESSION_KEY, user);
    }

    /**
     * 从Session中获取用户信息
     * @param session
     * @return
     */
    public static User getSessionUser(HttpSession session) {
        return (User) session.getAttribute(ConstantUtils.USERINFO_SESSION_KEY);
    }

    /**
     * 从HttpServletRequest中获取用户信息
     * @param request
     * @return
     */
    public static User getSessionUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 不创建新的会话
        return getSessionUser(request.getSession());
    }

    /**
     * 检查用户是否已登录
     * @param request
     * @return
     */
    public static boolean isUserLoggedIn(HttpServletRequest request) {
        return getSessionUser(request) != null;
    }

    /**
     * 检查用户是否有管理员权限
     * @param request
     * @return
     */
    public static boolean isAdminUser(HttpServletRequest request) {
        User user = getSessionUser(request);
        System.out.println(user);
        System.out.println(user.getRole());
        System.out.println(user != null);
        System.out.println(user.getRole() == 0);
        System.out.println(user != null && user.getRole() == 0);
        return user != null && user.getRole() == 0;
    }
}